package function;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import function.model.User;

public class Grouping {

	static void objectGrouping(List<User> userList) {
		Map<String, List<User>> result = new HashMap<>();
		for (User user : userList) {
			String group = user.getGroup();
			if (result.containsKey(group)) {
				List<User> groupList = result.get(group);
				groupList.add(user);
				result.put(group, groupList);
			} else {
				List<User> groupList = new ArrayList<>();
				groupList.add(user);
				result.put(group, groupList);
			}
		}
		print(result, "objectGrouping");
	}

	static void java8Grouping(List<User> userList) {
		Map<String, List<User>> result = userList.stream().collect(Collectors.groupingBy(User::getGroup));
		print(result, "java8Grouping");
	}

	static void print(Map<String, List<User>> map, String name) {
		System.out.println("********** " + name + " **********");
		for (String key : map.keySet()) {
			System.out.println(key + "组:");
			List<User> list = map.get(key);
			for (User user : list) {
				System.out.println(user);
			}
		}
	}

	public static void main(String[] args) {
		List<User> userList = new ArrayList<>();
		userList.add(new User("A", "狗蛋", 10));
		userList.add(new User("B", "铁柱", 12));
		userList.add(new User("C", "富贵", 13));
		userList.add(new User("A", "翠花", 14));
		userList.add(new User("C", "如花", 15));
		userList.add(new User("C", "大熊", 16));
		objectGrouping(userList);
		java8Grouping(userList);
	}
}
